package cn.xxm.scene.listener;

import cn.xxm.scene.bo.ModelExcel;
import cn.xxm.scene.constant.Constants;
import cn.xxm.scene.entity.RegistWhite;
import cn.xxm.scene.service.RegistWhiteService;
import cn.xxm.scene.utils.SpringContextUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author LWong
 * @date 2020/03/06
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener {
    private static final int BATCH_COUNT = 30;
    private Set<ModelExcel> datas = Sets.newHashSet();

    private RegistWhiteService registWhiteService;

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(o));
        //数据存储到list，
        ModelExcel modelExcel = (ModelExcel) o;

        datas.add(modelExcel);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (datas.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            datas.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 入库
     */
    private void saveData() {
        long startTime = System.currentTimeMillis();
        long step1 = System.currentTimeMillis();

        Set<ModelExcel> registWhiteList  = datas;
        log.info("{}条数据，开始存储数据库！", datas.size());
        insertBatchWhiteList(registWhiteList);
        log.info(">>>insertBatchWhiteList cost 【{}ms】", (step1 - startTime));

        log.info("存储数据库成功！");
    }

    public Set<ModelExcel> getDatas() {
        return datas;
    }

    public void setDatas(Set<ModelExcel> datas) {
        this.datas = datas;
    }


    private void insertBatchWhiteList(Set<ModelExcel> whiteExcelList) {
        // 2. 导入数据库

        if(null == registWhiteService){
            registWhiteService= SpringContextUtil.getBean(RegistWhiteService.class);
        }
        // 2.1 首先,excel文档去重复mobile



        // 2.2 查询有多少mobileNo重复的
        Set<String> existMobileList = registWhiteService.selectExistRecordByPhone(whiteExcelList);
        log.info(">>>exist mobile phone : {}", existMobileList);
        Set<RegistWhite> registWhiteList = new HashSet<>();
        whiteExcelList.forEach(item -> {
            if (!existMobileList.contains(item.getMbNumber())) {
                RegistWhite registWhite = new RegistWhite();
                registWhite.setId(IdWorker.getId());
                registWhite.setMobileNo(item.getMbNumber());
                registWhite.setIsSeed(Constants.WHITE_REGISTER_SEED_USER);
                registWhite.setIsLeaf(Constants.WHITE_REGISTER_LEAF);
                registWhite.setCreateDate(new Date());
                registWhite.setUpdateDate(new Date());
                registWhite.setStatus("1");
                registWhite.setEmail(item.getEmail());
                registWhiteList.add(registWhite);
            }
        });
        log.info(">>>有效记录条数:{}", registWhiteList.size());
        if (CollectionUtils.isNotEmpty(registWhiteList)) {
            registWhiteService.insertBatchWhiteList(registWhiteList);
        }
    }


}